<template>
  <div class="detail">
    <BannerInDetail :isShowControl="true" :isShowTitleText="true" :title="picture.img_name" :picture="picture" @updateLoad="updateLoad" />
    <!-- start 大图和图片的属性 -->
    <section class="download">
      <el-row :gutter="24">
        <el-col :span="14">
          <a v-if="picture.img_thumbnail" :href="picture.img_thumbnail|fillImgShot" target="_blank">
            <el-image :src="picture.img_thumbnail|fillImgShot" style="width:100%;height:518px;background-color:#f5f5f5;"
              fit="contain"></el-image>
          </a>
        </el-col>
        <el-col :span="10" style="height:518px;">
          <ul class="attribute-list">
            <li>
              <label>编号：</label>
              <span>{{picture.id}}</span>
            </li>
            <li>
              <label>格式：</label>
              <span v-if="picture.img_thumbnail">{{picture.img_thumbnail|getImgSuffix}}</span>
            </li>
            <li>
              <label>分类：</label>
              <span>{{picture.categoryName}}</span>
            </li>
            <!-- <li>
              <label>大小：</label>
              <span>{{(picture.file_size/1024).toFixed(2)}}MB</span>
            </li> -->
            <li>
              <el-button type="primary" plain size="small" v-for="(item,index) in picture.tagList.slice(0,5)"
                :key="index" @click="LinkToList(item)">{{item.name}}</el-button>
            </li>
          </ul>
          <el-form ref="form" :model="downloadform" label-width="120px" label-suffix="：" class="size-form" action="/api/down-file">
            <el-form-item v-for="(item,index) in picture.sizeList" :key="index" :label="item.title">
              <el-radio v-model="sizeRadio" :label="item" border>
                <span>{{item.size}}</span>
              </el-radio>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" round @click="downloadPicture()">免费下载</el-button>
              <!-- <i title="点击收藏" class="iconfont icon-shoucang" :style="{color:picture.isCollect?'#f56c6c':'#cdcdcd'}" style="cursor: pointer;margin-left:30px;line-height:40px;font-size:40px;vertical-align:middle;" @click="collect"></i> -->
              <el-button icon="el-icon-star-on" circle :type="picture.isCollect?'warning':''" @click="collect">
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </section>
    <!-- end 大图和图片的属性 -->
    <!-- start 猜你喜欢 -->
    <Like :likeTag_id="likeTag_id" :likeCategory="likeCategory" />
    <!-- end 猜你喜欢 -->
    <!-- start 图片信息 -->
    <section class="tags">
      <div class="tags-inner">
        <el-card class="box-card">
          <div slot="header">
            <span class="card-title">图片信息</span>
            <!-- <el-button style="float: right; padding: 3px 0" type="text" icon="">收起</el-button> -->
          </div>
          <el-form label-width="120px" label-suffix="：" class="size-form">
            <el-form-item label="标题"><span>{{picture.img_name}}</span></el-form-item>
            <el-form-item label="供图"><span>{{picture.img_designer}}</span></el-form-item>
            <el-form-item label="标签">
              <el-button type="info" plain size="mini" v-for="(item,index) in picture.tagList" :key="index" @click="LinkToList(item)">{{item.name}}</el-button>
            </el-form-item>
            <el-form-item label="位置">
              <el-button type="info" plain size="mini" v-for="(l,index) in formImgInfo.location" :key="index">{{l}}</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </section>
    <!-- end 图片信息 -->
  </div>
</template>
<script>
  import { mapState, mapMutations } from "vuex";
  import BannerInDetail from "@/components/BannerInDetail.vue";
  import Like from "@/components/Like.vue";
  export default {
    name: "detail",
    layout: "main",
    components: {
      BannerInDetail,
      Like
    },
    computed: {
      ...mapState("user", {
        isLogin: state => state.isLogin,
        showLoginModal: state => state.showLoginModal,
        userid: state => state.user_data.userid
      })
    },

    data() {
      return {
        bodyData: { id: '', uid: "" },//请求参数
        categoryList: [],
        id: "",
        likeTag_id: [],
        likeCategory: "",
        picture: {
          size: "",
          tags: "",
          tagList: [],
          img_url: "",
          picture: '',
          img_designer:''
        },
        sizeName: ["最大尺寸", "banner配图", "微信配图", "小图"],
        downloadform: {
          //下载的尺寸配置表，因为有的图可能是psd有的是raw或者ai格式，所以此处的title也得适应不同的值，不能写死
          maxSize: {
            title: "最大尺寸",
            width: "3900",
            height: "2080"
          },
          bannerSize: {
            title: "banner配图",
            width: "1920",
            height: "2080"
          },
          weXinSize: {
            title: "微信配图",
            width: "900",
            height: "383"
          },
          rawSize: {
            title: "PSD源文件",
            width: "3900",
            height: "2080"
          }
        },
        formImgInfo: {
          //图片信息
          location: ["欧洲", "西班牙"]
        },
        sizeRadio: { size: "" }
      };
    },
    mounted() {
      var id = this.$route.query.id;
      this.bodyData.id = id;
      this.load(this.bodyData)
      if (window.sessionStorage.getItem("tuyibo_userid") !== null) {
        var data = JSON.parse(window.sessionStorage.getItem("tuyibo_userid"));
        this.$store.commit("user/SET_isLogin", true);
        this.bodyData.uid = data.userid;
      }
      // var image_id = this.$route.query.id;
      // this.checkCollect(image_id);
    },
    watch: {
      // 'likeTag_id':{
      //   deep:true,
      //   handler: function(newV, oldV) {
      //     this.getLikeImgs(this.likeTag_id, this.likeCategory);
      //   }
      // },
      // isLogin (newVal, oldVal) {
      //   if(!newVal){
      //     this.bodyData.uid='';
      //   }else{
      //     if (window.sessionStorage.getItem("tuyibo_userid") !== null) {
      //       var data = JSON.parse(window.sessionStorage.getItem("tuyibo_userid"));
      //       this.bodyData.uid = data.userid;
      //     }
      //   }
      //   this.load(this.bodyData);
      // },
      $route: {
        handler: function() {
          var id = this.$route.query.id;
          this.bodyData.id=id
          this.load(this.bodyData);
        },
        // 深度观察监听
        deep: true
      }
    },
    methods: {
      updateLoad() {
        this.load(this.bodyData)
      },
      collect() {
        if (window.sessionStorage.getItem("tuyibo_userid") !== null) {
          var data = JSON.parse(window.sessionStorage.getItem("tuyibo_userid"));
          this.$axios.post("/api/web/collectPicture", {
              uid: data.userid,
              image_id: this.picture.id
            }).then(res => {
              if (res.data.code == -1) {
                this.$message.info(res.data.msg);
                this.picture.isCollect=false
                this.picture.collect_num--
              } else {
                this.$message.success(res.data.msg);
                this.picture.isCollect=true
                this.picture.collect_num++
              }
              // this.load(this.bodyData);
            }).catch(err => {
              console.log(err);
            });
        } else if( window.loginbox ){
          window.loginbox.show = true
        }
      },

      download(size) {
        var img_url = `${this.picture.oss_prepath}${this.picture.prefix_path}_${size}`;
        // return;
        var fillImgShot = this.$options.filters['fillImgShot']
        const url = fillImgShot(img_url);
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url, true);
        xmlhttp.responseType = "blob";
        xmlhttp.onload = function () {
          if (this.status == 200) {
            const blob = this.response;
            const link = document.createElement("a");
            link.href = window.URL.createObjectURL(blob);
            link.download = url.substring(url.lastIndexOf("/") + 1, url.length);

            //此写法兼容可火狐浏览器
            document.body.appendChild(link);

            const evt = document.createEvent("MouseEvents");
            evt.initEvent("click", false, false);
            link.dispatchEvent(evt);
            window.URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
          }
        };
        xmlhttp.send();
      },
      async add_download_counts(pars) {
        var r = await this.$axios.post('/api/web/add_download_counts', pars)
        return r;
      },

      // 下载图片
      async downloadPicture() {
        if (this.isLogin) {
          var size = this.sizeRadio.size;
          if (size === "") {
            this.$message.error("请选您择图片尺寸");
            return;
          }
          var pars = {}
          pars.down_size = size.split('.')[0]
          pars.down_format = size.split('.')[1]
          pars.down_type = 0
          pars.image_id = this.picture.id;
          pars.uid = this.userid;
          let res = await this.add_download_counts(pars);
          if (res.data.code == 1) {
            this.download(size);
          }
        } else if( window.loginbox ){
          window.loginbox.show = true
        }
      },


      LinkToList(obj) {
        this.$router.push({
          name: "list",
          path: "/list",
          query: {
            tag_id: obj.id,
            title: obj.name
          }
        });
      },
      // 整理图大小
      sortOutSize(picture) {
        var small = picture.img_thumbnail.split('_')[1]
        var size = picture.img_src + ',' + small
        size = size.split(',')
        var arr = [];
        if (this.sizeName.length >= size.length) {
          for (var i = 0; i < size.length; i++) {
            var s = {};
            s.size = size[i];
            s.title = this.sizeName[i];
            arr.push(s);
          }
          picture.sizeList = arr;

          return picture;
        }
      },

      load(data) {
        this.$axios.post("/api/web/getDetails", data).then(res => {
          var picture = res.data;
          picture = this.sortOutSize(picture);
          var tag_ids = picture.tagIds.split(",");
          var tags = picture["ti.tag_name"].split(",");
          var arr = [];
          for (var i = 0; i < tag_ids.length; i++) {
            var obj = {};
            obj.id = tag_ids[i];
            obj.name = tags[i];
            arr.push(obj);
          }
          // delete picture.tagIds
          delete picture["ti.tag_name"]
          picture.tagList = arr;
          this.picture = picture;
          var likeTag_id = []
          for(let item of this.picture.tagList){
            likeTag_id.push(item.id)  
          }
          var likeCategory = this.picture.category;
          this.likeTag_id = likeTag_id;
          this.likeCategory = likeCategory;
        })
      }
    }
  };
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
  @import "../assets/css/icon.css";

  .detail {
    min-height: 800px;

    .download {
      max-width: 1380px;
      padding: 0 16px;
      margin: 0 auto 24px;

      .attribute-list {
        list-style: none;
        background-color: @color-global-bg-color;
        padding: 16px 16px 0;
        margin-bottom: 16px;

        >li {
          font-size: 16px;
          margin-bottom: 12px;

          >.el-button {
            margin-bottom: 16px;
          }

          >label {
            font-weight: 600;
          }
        }
      }

      .size-form {
        border: 2px solid @color-border;
        padding-top: 16px;

        /deep/.el-form-item {
          margin-bottom: 17px;

          .el-form-item__label {
            font-weight: 600;
          }

          .el-radio.is-bordered {
            .el-radio__label {

              em,
              span {
                font-style: normal;
                display: inline-block;
                line-height: 1;
              }

              span {
                min-width: 3em;
              }

              em {
                padding: 0 5px;
              }
            }
          }
        }
      }
    }

    .tags {
      margin-bottom: 24px;

      .tags-inner {
        max-width: 1380px;
        padding: 0 16px;
        margin: 0 auto;
      }
    }
  }
</style>